//
//  AppDelegate+AppConfiguration.m
//  JSBaseProject
//
//  Created by Apple on 2017/11/7.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "AppDelegate+AppConfiguration.h"
#import "QMUIConfigurationTemplate.h"
#import "JSBaseNaviController.h"
#import "JSBaseViewController.h"
#import "JSBaseTabBarController.h"
#import "JSLoginViewController.h"



@implementation AppDelegate (AppConfiguration)

-(void) setupAppConfiguration{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];
    
    // 应用 QMUI Demo 皮肤
    NSString *themeClassName = [[NSUserDefaults standardUserDefaults] stringForKey:QDSelectedThemeClassName] ?: NSStringFromClass([QMUIConfigurationTemplate class]);
    [QDThemeManager sharedInstance].currentTheme = [[NSClassFromString(themeClassName) alloc] init];
    
    // QD自定义的全局样式渲染
    [QDCommonUI renderGlobalAppearances];
    
    // 预加载 QQ 表情，避免第一次使用时卡顿（可选）
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [QMUIQQEmotionManager emotionsForQQ];
    });
    
    [[UIButton appearance] setExclusiveTouch:YES];
    
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    
    //注册登录状态监听
    kWeakSelf(self)
    [[kNotificationCenter rac_addObserverForName:KNotificationLoginStateChange object:nil] subscribeNext:^(NSNotification *x) {
        kStrongSelf(self)
        JSLog(@"%@", x.object);
        JSLog(@"%@", x.name);
        JSLog(@"%@", x.userInfo);
         BOOL loginSuccess = [x.object boolValue];
        if (loginSuccess) {
            if (!self.mainTabBar || ![self.window.rootViewController isKindOfClass:[JSBaseTabBarController class]]) {
                [self setupAppViewControllers];
            }
        }else{
            [self setupLoginVc];
        }
        
    }];
}

-(void) initUserManager{
    if ([userManager loadUserInfo]) {
        [self setupAppViewControllers];
        // 更新用户信息
        [userManager updataUserInfo:^(BOOL success, NSString *des) {
            if (success) {
                JSLog(@"自动登录成功");
            }else{
                JSLog(@"自动登录失败 %@", des);
            }
        }];
//        [userManager autoLoginToServer:^(BOOL success, NSString *des) {
//            if (success) {
//                JSLog(@"自动登录成功");
//            }else{
//                JSLog(@"自动登录失败 %@", des);
//            }
//        }];
    }else{
        [self setupLoginVc];
    }
}
//MARK: 配置主体控制器
-(void) setupAppViewControllers{
    // 获取根视图信息
    NSDictionary *rootVCs = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"rootViewControllerList" ofType:@"plist"]];
    NSArray *vcArray = rootVCs[@"viewControllrs"];
    NSInteger i = 0;
    NSMutableArray *naviArray = @[].mutableCopy;
    for (NSDictionary *subVCInfo in vcArray) {
        NSString *title = subVCInfo[@"title"];
        NSString *image = subVCInfo[@"icon_tabBar"];
        NSString *slectImage = subVCInfo[@"icon_tabBar_select"];
        NSString *className  = subVCInfo[@"className"];
        NSString *locaKey    = subVCInfo[@"locaKey"];
        title = JSLocalizedString(locaKey);
        UIViewController *vc = [[NSClassFromString(className) alloc] init];
        vc.hidesBottomBarWhenPushed = NO;
        JSBaseNaviController *navi = [[JSBaseNaviController alloc] initWithRootViewController:vc];
        navi.tabBarItem = [QDUIHelper tabBarItemWithTitle:title image:[UIImageMake(image) imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:UIImageMake(slectImage) tag:i];
        [naviArray addObject:navi];
        i++;
    }
    JSBaseTabBarController *tabBarViewController = [[JSBaseTabBarController alloc] init];
    self.mainTabBar = tabBarViewController;
    // window root controller
    tabBarViewController.viewControllers = naviArray.copy;
    CATransition *anima = [CATransition animation];
    anima.type = @"cube";//设置动画的类型
    anima.subtype = kCATransitionFromRight; //设置动画的方向
    anima.duration = 0.3f;
    self.window.rootViewController = tabBarViewController;
    [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
}
//配置登录控制器
-(void) setupLoginVc{
    self.mainTabBar = nil;
    JSBaseNaviController *loginNavi =[[JSBaseNaviController alloc] initWithRootViewController:[JSLoginViewController new]];
    CATransition *anima = [CATransition animation];
    anima.type = @"fade";//设置动画的类型
    anima.subtype = kCATransitionFromRight; //设置动画的方向
    anima.duration = 0.3f;
    self.window.rootViewController = loginNavi;
    [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
}
-(void) setupAppFitstUsering{
    QMUILog(@"首次进入配置");
    // 1. 配置基本数据
    // 1.1 获取国家数据
    [userManager getCity:^(id respose, int status) {
        if (status != 200) {
            [JSAlertHelper showFailHideAfterDelay:5 text:@"国家数据获取失败" inView:nil animation:YES];
        }
    }];
    
}
-(void) setupAppThirdConfigurarion{
    QMUILog(@"第三方配置");
    // 融云
    if ([JSBaseConfiguration sharedJSBaseConfiguration].isUseRCIM) {
        [[RCIM sharedRCIM] initWithAppKey:@"lmxuhwaglztbd"];
        [RCIM sharedRCIM].receiveMessageDelegate = self;
        [RCIM sharedRCIM].connectionStatusDelegate = self;
        [RCIM sharedRCIM].userInfoDataSource = self;
    }
}
- (void)startLaunchingAnimation {
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    UIView *launchScreenView = [[NSBundle mainBundle] loadNibNamed:@"LaunchScreen" owner:self options:nil].firstObject;
    launchScreenView.frame = window.bounds;
    [window addSubview:launchScreenView];
    
    UIImageView *backgroundImageView = launchScreenView.subviews[0];
    backgroundImageView.clipsToBounds = YES;
    
    UIImageView *logoImageView = launchScreenView.subviews[1];
    UILabel *copyrightLabel = launchScreenView.subviews.lastObject;
    
    UIView *maskView = [[UIView alloc] initWithFrame:launchScreenView.bounds];
    maskView.backgroundColor = UIColorWhite;
    [launchScreenView insertSubview:maskView belowSubview:backgroundImageView];
    
    [launchScreenView layoutIfNeeded];
    
    
    [launchScreenView.constraints enumerateObjectsUsingBlock:^(__kindof NSLayoutConstraint * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.identifier isEqualToString:@"bottomAlign"]) {
            obj.active = NO;
            [NSLayoutConstraint constraintWithItem:backgroundImageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:launchScreenView attribute:NSLayoutAttributeTop multiplier:1 constant:NavigationContentTop].active = YES;
            *stop = YES;
        }
    }];
    
    [UIView animateWithDuration:.15 delay:0.9 options:QMUIViewAnimationOptionsCurveOut animations:^{
        [launchScreenView layoutIfNeeded];
        logoImageView.alpha = 0.0;
        copyrightLabel.alpha = 0;
    } completion:nil];
    [UIView animateWithDuration:1.2 delay:0.9 options:UIViewAnimationOptionCurveEaseOut animations:^{
        maskView.alpha = 0;
        backgroundImageView.alpha = 0;
    } completion:^(BOOL finished) {
        [launchScreenView removeFromSuperview];
    }];
}
@end
